<template>
    <div>
        <queryView v-model="queryParams" @query="getListData(1)" :options="options" @create="handleCreate" />
        <el-card shadow="hover">
            <el-table
                v-loading="tableDataLoading"
                :data="tableData"
                row-key="id"
                :tree-props="{ children: 'children' }"
                size="large"
                table-layout="auto"
                style="min-height: 500px">
                <el-table-column align="center" type="index" label="#" min-width="50" />
                <el-table-column align="center" prop="title" label="菜单名称" width="160" />
                <el-table-column align="center" label="图标" width="180">
                    <template #default="scope">
                        <div style="display: flex; align-items: center; justify-content: center">
                            <el-icon v-if="scope.row.icon" :size="25">
                                <component :is="scope.row.icon" />
                            </el-icon>
                            <span style="width: 100px; text-align: left; margin-left: 5px">{{ scope.row.icon }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="name" label="权限标识" width="160" />
                <el-table-column align="center" prop="path" label="路由地址" width="160" />
                <el-table-column align="center" prop="component" label="组件路径" width="160" />
                <el-table-column align="center" prop="sort" label="排序" width="160" />
                <!-- <el-table-column align="center" prop="parent" label="上级分类">
                  <template #default="scope">
                      <el-tag v-if="scope.row.parent">{{ scope.row.parent.name }}</el-tag>
                      <el-tag v-else>无</el-tag>
                  </template>
              </el-table-column> -->
                <!-- <el-table-column align="center" prop="status" label="状态">
                    <template #default="scope">
                        <el-switch
                            v-model="scope.row.status"
                            @change="handleSwitchChange($event, scope.row.id)"
                            :active-value="1"
                            :inactive-value="2" />
                    </template>
                </el-table-column> -->
                <el-table-column align="center" prop="created_at" label="创建时间" width="160" />
                <el-table-column align="center" fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleEdit(scope.row)"> 编辑 </el-button>
                        <el-button link type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 20px">
                <el-pagination
                    v-model:current-page="page"
                    v-model:page-size="pageSize"
                    @update:current-page="getListData"
                    @update:page-size="getListData"
                    layout="total,sizes,prev, pager, next,jumper"
                    size="small"
                    background
                    :page-sizes="[20, 50, 100, 200, 500]"
                    :total="total" />
            </div>
            <!-- 弹窗 -->
            <el-dialog
                v-model="dialogFormVisible"
                :title="formIsEdit ? '编辑' : '新增'"
                width="500px"
                destroy-on-close
                :close-on-click-modal="false">
                <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                    <el-form-item label="菜单名称" prop="title">
                        <el-input v-model="form.title" autocomplete="off" />
                    </el-form-item>

                    <el-form-item label="权限标识" prop="name">
                        <el-input v-model="form.name" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="路由地址" prop="path">
                        <el-input v-model="form.path" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="组件路径" prop="component">
                        <el-input v-model="form.component" autocomplete="off" />
                    </el-form-item>

                    <el-form-item label="上级菜单" prop="parent_id">
                        <el-tree-select
                            v-model="form.parent_id"
                            node-key="id"
                            :props="{
                                children: 'children',
                                label: 'name'
                            }"
                            check-strictly
                            :default-checked-keys="[form.parent_id]"
                            :data="tableData"
                            :render-after-expand="false"
                            style="" />
                        <!-- <el-select v-model="form.parent_id">
                          <template v-for="item in options.categories" :key="item.id">
                              <el-option :label="item.name" :value="item?.id"></el-option>
                          </template>
                      </el-select> -->
                    </el-form-item>
                    <el-form-item label="图标" prop="icon">
                        <el-input v-model="form.icon" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="排序" prop="sort" style="width: 180px">
                        <el-input v-model="form.sort" type="number" autocomplete="off" />
                    </el-form-item>
                    <!-- <el-form-item label="状态" prop="status">
                        <el-switch v-model="form.status" :active-value="1" :inactive-value="2" />
                    </el-form-item> -->
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="handleSubmit(formRef)">确 定</el-button>
                    </div>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup lang="ts">
    import { apiMenu } from '@/api/restful'
    import type { FormInstance, FormRules } from 'element-plus'
    import type { Menu } from '@/types/global'
    import ymiUpload from '@/components/ymi/ymiUpload.vue'
    import queryView from './queryView.vue'
    const total = ref(0)
    const page = ref(1)
    const pageSize = ref(20)
    const tableDataLoading = ref(true)
    const tableData = ref<Menu[]>([])
    const options = ref({
        categories: <Menu[]>[]
    })
    const queryParams = ref({})

    const dialogFormVisible = ref(false)
    const formRef = ref<FormInstance>()
    const formIsEdit = ref(false)
    const form = ref<Menu>({
        id: '',
        status: 2,
        name: '',
        icon: '',
        parent_id: '',
        sort: 0
    })

    const rules = reactive<FormRules<Menu>>({
        title: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        name: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
        path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }]
    })
    onMounted(() => {
        getListData()
    })

    /**
     * 获取列表数据
     */
    const getListData = (nowPage?: number) => {
        tableDataLoading.value = true
        if (nowPage) page.value = nowPage
        const paramsData = {
            ...{ page: page.value, pageSize: pageSize.value },
            ...queryParams.value
        }
        apiMenu(paramsData, 'GET')
            .then((res) => {
                tableDataLoading.value = false
                tableData.value = res.data?.data
                total.value = res.data?.total
                options.value = res.data?.options
            })
            .catch(() => {
                tableDataLoading.value = false
            })
    }
    const handleCreate = () => {
        formIsEdit.value = false
        form.value = {} as Menu
        dialogFormVisible.value = true
    }

    /**
     * 处理表单提交
     * @param formEl
     */
    const handleSubmit = async (formEl: FormInstance | undefined) => {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (!valid) return
            dialogFormVisible.value = false
            if (formIsEdit.value) {
                updateRequest(form.value, '保存成功')
                return
            }
            apiMenu(form.value, 'POST').then((res) => {
                ElMessage({
                    type: 'success',
                    message: '新增成功'
                })
                getListData()
            })
        })
    }

    /**
     * 删除
     */
    const handleDelete = (id: number) => {
        ElMessageBox.confirm('该分类下的所有子分类也都将同步删除，确认删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            apiMenu({ id }, 'DELETE').then((res) => {
                ElMessage({
                    type: 'success',
                    message: '删除成功'
                })
                getListData()
                console.log(res)
            })
        })
    }
    /**
     * 编辑
     */
    const handleEdit = (row: Menu) => {
        console.log(row)
        form.value = { ...row }
        formIsEdit.value = true
        dialogFormVisible.value = true
    }
    /**
     * 更新请求
     * @param params
     * @param msg
     */
    const updateRequest = (params: any, msg = '更新成功') => {
        apiMenu(params, 'PUT').then((res) => {
            ElMessage({
                type: 'success',
                message: msg
            })
            getListData()
        })
    }
    /**
     * 处理表格数据switch事件
     * @param value
     * @param id
     */
    const handleSwitchChange = (value: any, id: number) => {
        updateRequest({ id, status: value }, '更新成功')
    }
</script>

<style></style>
